package cn.rengy.web.framework.antireptile.config;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.rengy.web.framework.antireptile.interceptor.AntiReptileInterceptor;
import cn.rengy.web.framework.antireptile.rule.AntiReptileRule;
import cn.rengy.web.framework.antireptile.rule.IpRule;
import cn.rengy.web.framework.antireptile.rule.RuleActuator;

/**
 */
@Configuration
@EnableConfigurationProperties(AntiReptileProperties.class)
@ConditionalOnProperty(prefix = "anti.reptile.manager", value = "enabled", havingValue = "true", matchIfMissing = false)
public class AntiReptileAutoConfig {


    @Bean
    @ConditionalOnProperty(prefix = "anti.reptile.manager.ip-rule",value = "enabled", havingValue = "true", matchIfMissing = true)
    public IpRule ipRule(){
        return new IpRule();
    }

//    @Bean
//    @ConditionalOnProperty(prefix = "anti.reptile.manager.ua-rule",value = "enabled", havingValue = "true", matchIfMissing = false)
//    public UaRule uaRule() {
//        return new UaRule();
//    }


    @Bean
    @ConditionalOnBean(IpRule.class)
    public RuleActuator ruleActuator(final List<AntiReptileRule> rules){
        final List<AntiReptileRule> antiReptileRules = rules.stream()
                .sorted(Comparator.comparingInt(AntiReptileRule::getOrder)).collect(Collectors.toList());
        return new RuleActuator(antiReptileRules);
    }

    @Bean
    @ConditionalOnBean(RuleActuator.class)
    public AntiReptileInterceptor antiReptileInterceptor() {
        return new AntiReptileInterceptor();
    }

}
